# coding: utf-8
# Project：PyCharmMiscProject
# File：文件操作作业.py
# Author：liuchuanzhi
# Date
# ：2025/4/23 19:42
# IDE：PyCharm
#记事本
import os
def create_write_file():
    filename=input("请输入一个文件名：")
    text=input("请输入要写入的内容：")
    with open(filename,"w") as file:
        file.write(text)
    abs_path=os.path.abspath(filename)
    print(f"文件{filename}创建并写入成功")
    print(f"文件被保存在：{abs_path}")

def read_file():
    filename=input("请输入要读取的文件名：")
    try:
        file=open(filename,"r")
        content=file.read()
        print("文件内容为：",content)
    except FileNotFoundError:
        print(f"{filename}未找到")

def append_to_file():
    filename=input("请输入文件名：")
    text=input("请输入要追加的内容：")
    file=open(filename,"a")
    file.write(text)
    print(f"{text}已追加到文件中")

def delete_file():
    filename=input("请输入要删除的文件名：")
    try:
        os.remove(filename)
        print(f"已成功删除文件：{os.path.abspath(filename)}")
    except FileNotFoundError:
        print(f"路径{filename}不存在，删除失败")
    except Exception as e:
        print(f"删除时发生错误：{str(e)}")

def motify_file():
    filename=input("请输入文件名：")
    try:
        with open(filename,"r")as file:
            content=file.read()
        old_text=input("请输入要替换的原内容：")
        new_text=input("请输入替换后的新内容：")
        new_content=content.replace(old_text,new_text)

        with open(filename,"w")as file:
            file.write(new_content)

        if new_content!=content:
            print(f"已将文件中的‘{old_text}’替换为‘{new_text}’")
        else:
            print(f"未找到需要替换的内容‘{old_text}’")
    except FileNotFoundError:
        print(f"路径{filename}未找到，无法修改")

def mynotebook():
    while True:
        print("---*简单记事本程序*___")
        print("1.创建并写入文件")
        print("2.读取文件")
        print("3.追加文本到文件")
        print("4.替换文件内容")
        print("5.删除文件")
        print("6.退出")

        choice=input("请输入选项编号：")
        if choice=="1":
            create_write_file()#
        elif choice=="2":
            read_file()#
        elif choice=="3":
            append_to_file()#
        elif choice=="4":
            motify_file()#
        elif choice=="5":
            delete_file()#
        elif choice=="6":
            break#


if __name__=="__main__":
    mynotebook()